package cn.antia.cwin.window;

import cn.antia.cwin.page.StrutsAction;
import cn.antia.cep.page.action.ActionException;
import cn.antia.cep.common.AntiaException;
import cn.antia.cep.common.SysExceptionTool;
import static cn.antia.cwin.window.WindowConst.*;
import cn.antia.cwin.Cele;
import cn.antia.cwin.ConfigPoolHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Iterator;
import java.util.HashMap;

/**
 * User: Jacob Xiao
 * Date: 2008-7-23
 * Time: 17:53:38
 */
public class WindowAction extends StrutsAction {
    private SingleWindow window;

    protected String action() throws AntiaException {
        String action = request.getParameter(JWAS_ACTION_PARANAME) == null ? "" : request.getParameter(JWAS_ACTION_PARANAME);
        if (action == null || action.equals("")) {
            return init(request);
        }
        String windowId = request.getParameter(WindowConst.JWAS_SINGLE_WINDOW_ID);
        if (windowId == null || windowId.equals("")) {
            request.setAttribute("msg","没有指定Window");
            return "error";
        }
        window = ConfigPoolHelper.getSingleWindow(windowId);
        return "single";
    }

    /**
	 * 将Window信息装入session
	 * @param request HttpServletRequest
     * @return return
	 */
	protected String init(HttpServletRequest request){
		String id = request.getParameter("id");		//window id
		if(id == null || id.trim().length() < 1){
			ActionException ae = new ActionException("012","Not get a window ID");
			SysExceptionTool.addExceptionInfo(ae);
			throw ae;
		}
		window = ConfigPoolHelper.getSingleWindow(id);
		if(window == null){
			ActionException ae = new ActionException("012","Not found a window by ID=" + id);
			SysExceptionTool.addExceptionInfo(ae);
			throw ae;
		}
		Map map = request.getParameterMap();
        Iterator pamas = map.keySet().iterator();
        //限制字段
        Map<String,String> limits = new HashMap<String, String>();
        //额外的---- 暂不做支持
        Map<String,String> extra = new HashMap<String, String>();
        
        String parm,pvalue;
        while(pamas.hasNext()){
        	parm = (String)pamas.next();
        	pvalue = request.getParameter(parm);
        	//如果指定action
        	if(parm.equals("was")){
        		window.setAction(pvalue);
        		continue;
        	}
        	if(parm.equals("id")){
        		continue;
        	}
        	//查看是否有这个字段
        	if(window.hasField(parm)) {
                if (pvalue != null && pvalue.length() > 0) {
                    limits.put(parm, pvalue);
                }
            }else {
                extra.put(parm, pvalue);
            }
        }
        request.setAttribute(JWAS_SINGLE_WINDOW_ID,window);
        request.setAttribute(JWAS_LIMITS_PARANAME, limits);
        request.setAttribute(JWAS_EXTRA_PARANAME, extra);
        return "single";
    }
}
